<template>
  <div :class="f" :style="{height:height,width:width}"/>
</template>
<script>
import echarts from '@/assets/lib/echarts'
import { debounce } from '../../../common/js/commons'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '420px'
    },
    height: {
      type: String,
      default: '420px'
    },
    chartData: {
      type: Array,
      default: null
    },
    chartCount: {
      type: Number,
      default: 0
    },
      pieRadius: {
      type: Array,
      default: ()=>{
          return [60 ,120]
      }
    }
  },
  data() {
    return {
      f: "",
      chart: null
    }
  },
  watch: {
    chartData: {
      deep: true,
      handler(val) {
        if (val.length > 0) {
          this.initChart()
        }
      }
    }
  },
  mounted() {
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      let colorOptions = ['#40c1f9','#fe6c67','#fb9426','#ffda50','#9c27b0','#8bc34a']
      this.chart = echarts.init(this.$el, 'macarons')
      this.chart.setOption({

        title: {
            text: '总数',
            subtext: this.chartCount,
            left: 'center'
        },
          tooltip: {
              trigger: 'item',
              formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          legend: {
              left: 'center',
              top: 'bottom',
              data: this.chartData.map(item => {
                  return item.name
              })
          },
          toolbox: {
              show: true,
              feature: {
                  mark: {show: true},
                  dataView: {show: true, readOnly: false},
                  magicType: {
                      show: true,
                      type: ['pie', 'funnel']
                  },
                  restore: {show: true},
                  saveAsImage: {show: true}
              }
          },
          color:colorOptions,
          series: [
              {
                  name: '检查项对比',
                  type: 'pie',
                  radius: this.pieRadius,
                  center: ['50%', '40%'],
                  roseType: 'radius',
                  label: {
                      show: false
                  },
                  emphasis: {
                      label: {
                          show: true
                      }
                  },
                  data: this.chartData
              }
          ]
      })
        this.chart.on('click', (params) => {
            this.$emit('chartClickCheckItem', params)
      })
    }
  }
}
</script>
